package com.pzl.vca;

import android.util.Log;

import org.java_websocket.WebSocket;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.nio.ByteBuffer;

//数据接收客户端
public class NetReceiver {
    public static final String TAG = "jinx_vca_NetReceiver";

    private INet INet;
    MyWebSocketClient myWebSocketClient;
    private WebSocket webSocket;
    private String ip;

    public NetReceiver(INet INet, String ip) {
        this.INet = INet;
        this.ip = ip;
    }

    public void start() {
        try {
            URI url = new URI(ip);
            myWebSocketClient = new MyWebSocketClient(url);
            myWebSocketClient.connect();
        } catch (Exception e) {
            e.printStackTrace();
            Log.i(TAG, "NetReceiver start 异常 ：" + e.getMessage());
        }
    }


    private class MyWebSocketClient extends WebSocketClient {

        public MyWebSocketClient(URI serverURI) {
            super(serverURI);
        }

        @Override
        public void onOpen(ServerHandshake serverHandshake) {
            Log.i(TAG, "NetReceiver 打开 socket  onOpen  ");
        }

        @Override
        public void onMessage(String s) {
            Log.i(TAG, "NetReceiver onMessage   : " + s);
        }

        @Override
        public void onMessage(ByteBuffer bytes) {
            Log.i(TAG, "NetReceiver 消息长度  : " + bytes.remaining());
            byte[] buf = new byte[bytes.remaining()];
            bytes.get(buf);
            INet.onReceveData(buf);
        }

        @Override
        public void onClose(int i, String s, boolean b) {
            Log.i(TAG, "NetReceiver onClose: " + s);
        }

        @Override
        public void onError(Exception e) {
            Log.i(TAG, "NetReceiver onError: " + e.getMessage());
        }
    }

    public interface INet {
        void onReceveData(byte[] data);
    }

}
